package com.freesun.shop.controller;

import com.freesun.shop.entity.User;
import com.freesun.shop.param.LoginParam;
import com.freesun.shop.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public ResponseEntity<Object> login(@RequestBody LoginParam loginParam){
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginParam.getPrincipal(), "WX_LOGIN");
        Subject subject = SecurityUtils.getSubject();
        String token=null;
        Map<String, Object> result = new HashMap<>();
        try {
            subject.login(usernamePasswordToken);

            token = subject.getSession().getId().toString();
            User user = (User) subject.getPrincipal();
            userService.updateUserLoginRec(user);
            result.put("nickName", user.getNickName());
            result.put("userStutas", user.getStatus());
            result.put("access_token", token);
            return ResponseEntity.ok(result);
        } catch (AuthenticationException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @ApiOperation("新用户第一次登录成功后,后台没有保存到用户名,我们在小程序中通过发请求修改数据库里面的信息")
    @PutMapping("/p/user/setUserInfo")
    public ResponseEntity<Void> updateUserInfo(@RequestBody User user) {
        User userCurrent = (User) SecurityUtils.getSubject().getPrincipal();
        userService.updateUser(userCurrent.getUserId(), user.getNickName(), user.getPic());

        return ResponseEntity.ok().build();
    }

}
